import { defineComponent, ref, reactive, onMounted, unref } from 'vue';
import { Button, Modal, Form, Input, Select, Table, Radio, Space, message } from 'ant-design-vue';
import { FundProjectionScreenOutlined, SearchOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';
import modeler from '@/store/modules/modeler';
import { getFormJSON, runProcSimulation } from '@/api/flow/index';
import { getFormDataJson, getNextNodes } from '@/utils/common';
import { taskAttr } from '@/store/modules/taskAttr';
import { gateWayAttr } from '@/store/modules/gateWay';
import { useModal } from '@/hooks/useModal/useModal';
import userSingle from '@/components/system/orgUserSingle/userSingle.vue';

// 仿真参数类型定义
interface SimulationParam {
  param: string;
  type: 'form' | 'option';
  source: string;
  preset: any;
  optionList?: any[];
}

// 仿真用例类型定义
interface SimulationCase {
  id: string;
  caseName: string;
  caseDesc: string;
  starter: string;
  starterName: string;
  params: SimulationParam[];
  result?: string;
  lastExecTime?: string;
}

// 组件属性类型定义
interface SimulationProps {
  processInfo: any;
  onSimulationStart?: () => void;
  onSimulationComplete?: (result: any) => void;
}

export default defineComponent({
  name: 'BpmnSimulation',
  props: {
    processInfo: {
      type: Object as PropType<any>,
      required: true
    },
    onSimulationStart: {
      type: Function as PropType<() => void>,
      default: () => {}
    },
    onSimulationComplete: {
      type: Function as PropType<(result: any) => void>,
      default: () => {}
    }
  },
  
  setup(props) {
    defineComponent({
        userSingle
    })
    const visible = ref(false);
    const loading = ref(false);
    const confirmLoading = ref(false);
    const editMode = ref(false); 
    const currentCaseId = ref(''); 
    
    // 表单数据
    const modelItems = reactive({
      useCasesName: '',
      useCasesRemark: '',
      starter: '',
      starterName: ''
    });
    
    // 数据源
    const casesData = ref<SimulationCase[]>([]); // 用例列表
    const formKeyList = ref<any[]>([]); // 表单字段列表
    const dataSource = ref<SimulationParam[]>([]); // 参数设置列表
    
    // 用户选择组件引用
    const userSingleRef = ref<InstanceType<typeof userSingle> | null>(null);
    const editDrawerBindValue = reactive({
        defaultSelectData: [],
        runType:'',
        modelType:'',
    });
    const [ModalRender, modalRef] = useModal();
    
    // 获取modeler实例
    const modelerStore = modeler();
    
    // 表格列定义
    const caseColumns = [
      {
        title: '用例名称',
        dataIndex: 'caseName',
        key: 'caseName',
        width: 150
      },
      {
        title: '用例说明',
        dataIndex: 'caseDesc',
        key: 'caseDesc',
        width: 200
      },
      {
        title: '起草人',
        dataIndex: 'starterName',
        key: 'starterName',
        width: 120
      },
      {
        title: '执行结果',
        dataIndex: 'result',
        key: 'result',
        width: 120,
        render: (text: string) => {
          const statusMap = {
            success: { text: '成功', color: 'green' },
            failed: { text: '失败', color: 'red' },
            pending: { text: '执行中', color: 'blue' }
          };
          const status = statusMap[text] || { text: '未执行', color: 'gray' };
          return <span style={{ color: status.color }}>{status.text}</span>;
        }
      },
      {
        title: '最近执行时间',
        dataIndex: 'lastExecTime',
        key: 'lastExecTime',
        width: 180
      },
      {
        title: '操作',
        key: 'action',
        width: 150,
        render: (_, record: SimulationCase) => (
          <Space size="middle">
            <Button type="link" onClick={() => editCase(record)}>编辑</Button>
            <Button type="link" onClick={() => deleteCase(record.id)}>删除</Button>
            <Button type="link" onClick={() => runSimulation(record)}>执行</Button>
          </Space>
        )
      }
    ];
    
    // 参数设置表格列定义
    const paramColumns = [
      {
        title: '参数',
        dataIndex: 'param',
        key: 'param',
        width: 150,
        render: (text, record: SimulationParam) => {
          if (record.type === 'form') {
            return (
              <Select
                value={record.preset}
                style={{ width: '100%' }}
                onChange={(val) => updateParamPreset(record.param, val)}
              >
                {formKeyList.value.map(item => (
                  <Select.Option key={item.id} value={item.id}>{item.label}</Select.Option>
                ))}
              </Select>
            );
          }
          return text;
        }
      },
      {
        title: '参数类型',
        dataIndex: 'type',
        key: 'type',
        width: 120
      },
      {
        title: '参数来源',
        dataIndex: 'source',
        key: 'source',
        width: 120
      },
      {
        title: '参数值预设',
        dataIndex: 'preset',
        key: 'preset',
        render: (text, record: SimulationParam) => {
          if (record.type === 'option') {
            return (
              <Radio.Group
                value={record.preset}
                onChange={(e) => updateParamPreset(record.param, e.target.value)}
              >
                {record.optionList?.map(item => (
                  <Radio key={item.id} value={item.id}>{item.name}</Radio>
                )) || []}
              </Radio.Group>
            );
          }
          return text;
        }
      }
    ];
    
    // 获取表单字段
    const fetchFormKeys = async () => {
      try {
        const formJson = await getFormJSON({ 
          processkey: props.processInfo.id, 
          taskid: '' 
        });
        
        if (formJson.error === '200') {
          const mapJSON = JSON.parse(formJson.result.mapJson);
          formKeyList.value = getFormDataJson(mapJSON.list);
        } else {
          message.error('获取表单数据失败');
        }
      } catch (error) {
        console.error('获取表单数据出错:', error);
        message.error('获取表单数据出错');
      }
    };
    
    // 获取网关信息
    const fetchGateWayInfo = () => {
      const gateWayStore = gateWayAttr();
      return gateWayStore.gateWays.filter(
        item => item.GATEWAY_TYPE !== 'JoinGateway' && 
                item.GATEWAY_TYPE !== 'ParallelGateway'
      );
    };
    
    // 生成参数列表
    const generateParamList = async () => {
      dataSource.value = [];
      const elementRegistry = modelerStore.getModeler;
      const gateWayInfoList = fetchGateWayInfo();
      
      // 处理网关参数
      if (gateWayInfoList.length > 0 && elementRegistry) {
        for (let i = 0; i < gateWayInfoList.length; i++) {
          const flows = getNextNodes(
            gateWayInfoList[i].GATEWAY_NO,
            gateWayInfoList[i].GATEWAY_RUN_TYPE,
            elementRegistry
          );
          
          if (flows.nodeList.length > 0) {
            const netxInfo = {
              param: gateWayInfoList[i].GATEWAY_NO,
              type: 'option',
              source: '人工决策',
              preset: flows.nodeList[0]?.id,
              optionList: flows.nodeList
            };
            dataSource.value.push(netxInfo);
          }
        }
      }
      
      // 处理表单参数
      if (formKeyList.value.length > 0) {
        for (let i = 0; i < formKeyList.value.length; i++) {
          const netxInfo = {
            param: formKeyList.value[i].id,
            type: 'form',
            source: '业务表单项',
            preset: undefined
          };
          dataSource.value.push(netxInfo);
        }
      }
    };
    
    const updateParamPreset = (param: string, value: any) => {
      const index = dataSource.value.findIndex(item => item.param === param);
      if (index !== -1) {
        dataSource.value[index].preset = value;
      }
    };
    
    // 打开仿真设置弹窗
    const openSimulationModal = async () => {
      loading.value = true;
      try {
        await fetchFormKeys();
        await generateParamList();
        visible.value = true;
      } catch (error) {
        console.error('加载仿真数据失败:', error);
        message.error('加载仿真数据失败');
      } finally {
        loading.value = false;
      }
    };
    
    const createNewCase = () => {
      editMode.value = false;
      currentCaseId.value = '';

      modelItems.useCasesName = '';
      modelItems.useCasesRemark = '';
      modelItems.starter = '';
      modelItems.starterName = '';
      
      generateParamList();
      
      paramModalVisible.value = true;
    };

    const editCase = (caseData: SimulationCase) => {
      editMode.value = true;
      currentCaseId.value = caseData.id;
  
      modelItems.useCasesName = caseData.caseName;
      modelItems.useCasesRemark = caseData.caseDesc;
      modelItems.starter = caseData.starter;
      modelItems.starterName = caseData.starterName;

      dataSource.value = cloneDeep(caseData.params);
      
      paramModalVisible.value = true;
    };
    
    // 删除用例
    const deleteCase = (id: string) => {
      casesData.value = casesData.value.filter(item => item.id !== id);
      message.success('删除成功');
    };
    
    // 保存用例
    const saveCase = () => {
      if (!modelItems.useCasesName) {
        message.warning('请输入用例名称');
        return;
      }
      
      if (!modelItems.starter) {
        message.warning('请选择起草人');
        return;
      }
      
      const newCase: SimulationCase = {
        id: currentCaseId.value || `case_${Date.now()}`,
        caseName: modelItems.useCasesName,
        caseDesc: modelItems.useCasesRemark,
        starter: modelItems.starter,
        starterName: modelItems.starterName,
        params: cloneDeep(dataSource.value)
      };
      
      if (editMode.value) {
        const index = casesData.value.findIndex(item => item.id === currentCaseId.value);
        if (index !== -1) {
          casesData.value[index] = newCase;
        }
      } else {
        casesData.value.push(newCase);
      }
      
      paramModalVisible.value = false;
      message.success(editMode.value ? '更新成功' : '创建成功');
    };
    
    // 打开选择起草人弹窗
    const openModal = async() => {
      ModalRender.show({
        title: '选择起草人',
        width: '70%',
        destroyOnClose: true,
        content: () => {
            return <userSingle  ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userSingle>;
        },
        // 确定方法执行
        onOk: async (values) => {
            const res = await userSingleRef.value?.handleSubmit();
            if (!res) return;
            modelItems.starter = res.NO;
            modelItems.starterName = res.NAME;
        },
      });
    };
    
    // 执行流程仿真
    const runSimulation = async (caseData: SimulationCase) => {
      if (confirmLoading.value) return;
      
      confirmLoading.value = true;
      props.onSimulationStart();
      
      try {
        // 获取表单数据
        const formJson = await getFormJSON({ 
          processkey: props.processInfo.id, 
          taskid: '' 
        });
        
        if (formJson.error !== '200') {
          throw new Error('未绑定表单');
        }
        
        const mapJSON = JSON.parse(formJson.result.mapJson);
        const keyList = getFormDataJson(mapJSON.list);
        
        // 构建数据JSON
        const dataJson = keyList.reduce((acc, item) => {
          const keyObj = caseData.params.find(
            key => key.param === item.id && key.type === 'form'
          );
          if (keyObj) {
            acc[item.id] = keyObj.preset; 
          } else {
            acc[item.id] = ''; 
          }
          return acc;
        }, {});
        
        // 处理网关参数
        const gateWayObjs = caseData.params.filter(
          key => key.type === 'option'
        );
        let humanSelectedNodes = [];
        
        if (gateWayObjs.length > 0) {
          for (let i = 0; i < gateWayObjs.length; i++) {
            const humanSelectedNode = {
              gateWayId: gateWayObjs[i].param,
              selectNodeId: gateWayObjs[i].preset
            };
            humanSelectedNodes.push(humanSelectedNode);
          }
        }
        
        // 启动流程仿真
        const postData = {
          starter: caseData.starter,
          flowName: props.processInfo.name,
          processInstanceId: "",
          processDefinitionId: props.processInfo.id, 
          businessKey: "",
          humanSelectedNodes: JSON.stringify(humanSelectedNodes)
        };
        
        const result = await runProcSimulation(postData);
        
        // 更新用例状态
        const index = casesData.value.findIndex(item => item.id === caseData.id);
        if (index !== -1) {
          casesData.value[index].result = 'success';
          casesData.value[index].lastExecTime = new Date().toISOString();
        }
        
        message.success('流程仿真启动成功');
        props.onSimulationComplete(result);
      } catch (error: any) {
        console.error('流程仿真启动失败:', error);
        message.error(error.message || '流程仿真启动失败');
      } finally {
        confirmLoading.value = false;
      }
    };
    
    // 关闭主弹窗
    const closeModal = () => {
      visible.value = false;
    };
    
    // 参数设置弹窗状态
    const paramModalVisible = ref(false);
    
    return () => (
      <>
        <Button
          ghost
          type="primary"
          icon={<FundProjectionScreenOutlined />}
          onClick={openSimulationModal}
        >
          流程仿真
        </Button>
        
        {/* 主弹窗 */}
        <Modal
          title="流程仿真"
          visible={visible.value}
          onCancel={closeModal}
          footer={[
            <Button key="cancel" onClick={closeModal}>
              取消
            </Button>,
            <Button 
              key="create" 
              type="primary" 
              onClick={createNewCase}
              disabled={loading.value}
            >
              新增仿真用例
            </Button>
          ]}
          width={900}
          destroyOnClose
        >
          <Table
            columns={caseColumns}
            dataSource={casesData.value}
            loading={loading.value}
            bordered
            pagination={false}
            rowKey="id"
          />
        </Modal>
        
        {/* 参数设置弹窗 */}
        <Modal
          title={editMode.value ? '编辑仿真用例' : '新建仿真用例'}
          visible={paramModalVisible.value}
          onCancel={() => { paramModalVisible.value = false; }}
          onOk={saveCase}
          okText="保存"
          cancelText="取消"
          width={800}
          destroyOnClose
        >
          <Form layout="vertical">
            <Form.Item label="用例名称">
              <Input
                value={modelItems.useCasesName}
                onChange={(e) => { modelItems.useCasesName = e.target.value; }}
                placeholder="请输入用例名称"
              />
            </Form.Item>
            
            <Form.Item label="用例说明">
              <Input.TextArea
                value={modelItems.useCasesRemark}
                onChange={(e) => { modelItems.useCasesRemark = e.target.value; }}
                placeholder="请输入用例说明"
              />
            </Form.Item>
            
            <Form.Item label="起草人">
              <Input
                value={modelItems.starterName || '请选择'}
                onClick={openModal}
                readOnly
                placeholder="请选择起草人"
                suffix={<CloseOutlined onClick={() => { modelItems.starter = ''; modelItems.starterName = ''; }} />}
                style={{ cursor: 'pointer' }}
              />
            </Form.Item>
            
            <Form.Item label="参数预设置">
              <Table
                columns={paramColumns}
                dataSource={dataSource.value}
                bordered
                pagination={false}
                rowKey="param"
              />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
});